package xyz.xtt.equity.utils;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AESUtil {
	private static final String FIXED_KEY = "RY3rwascwU8cARmX3VsTTW8f";

	public static String generateKey() throws Exception {
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		keyGenerator.init(256); // 设置密钥大小（128位、192位或256位）
		return keyGenerator.generateKey().toString();
	}

	// 加密方法
	public static String encrypt(String data) {
		// 创建密钥对象
		SecretKeySpec secretKeySpec = new SecretKeySpec(FIXED_KEY.getBytes(), "AES");

		// 加密数据
		byte[] encryptedBytes = null;
		try {
			// 创建 Cipher 实例
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // 使用 ECB 模式和 PKCS5 填充
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			encryptedBytes = cipher.doFinal(data.getBytes());
		} catch (Exception e) {
			log.info("encrypt ex:{}", e.getMessage(), e);
			throw new IllegalStateException(e.getCause());
		}
		return Base64.getEncoder().encodeToString(encryptedBytes); // 转为 Base64 字符串
	}

	// 解密方法
	public static String decrypt(String encryptedData) {
		// 创建密钥对象
		SecretKeySpec secretKeySpec = new SecretKeySpec(FIXED_KEY.getBytes(), "AES");
		byte[] originalBytes = null;
		try {
			// 创建 Cipher 实例
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // 使用 ECB 模式和 PKCS5 填充
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

			// 解密数据
			byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
			originalBytes = cipher.doFinal(decodedBytes);
		} catch (Exception e) {
			log.info("decrypt ex:{}", e.getMessage(), e);
			throw new IllegalStateException(e.getCause());
		}
		return new String(originalBytes);
	}

}
